package com.smit.livevideo.sample.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.WindowManager;

import com.smit.livevideo.sample.fragment.FragmentUtil;
import com.smit.livevideo.sample.util.SDKAPIUtil;
import com.smit.utils.LogUtil;
import com.smit.utils.NetUtil;

import java.util.Stack;

/**
 * Created by smfang on 2015/11/24.
 * 虚基类Activity，存放一些LauncherActivity和LivevideoActivity公共的方法
 */
public abstract class BaseActivity extends Activity
{
    private static final String TAG = BaseActivity.class.getSimpleName();
    private static Stack<Activity> activityList = new Stack<Activity>();

    BroadcastReceiver netConnectReceiver = new BroadcastReceiver()
    {
        public void onReceive(Context context, Intent intent)
        {
            if (intent == null)
            {
                LogUtil.trace(TAG, "intent is null!");
                return;
            }

            String action = intent.getAction();
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action))
            {
                boolean bNetworkOk = NetUtil.isNetworkOk(BaseActivity.this);
                LogUtil.debug(TAG, "bNetworkOk = " + bNetworkOk);
                if (bNetworkOk)
                {
                    onNetworkOk();
                }
                else
                {
                    onNetworkFail();
                }

            }
        }
    };

    private BroadcastReceiver homePressReceiver = new BroadcastReceiver()
    {
        static final String SYSTEM_DIALOG_REASON_KEY = "REASON";
        static final String SYSTEM_DIALOG_REASON_HOME_KEY = "HOMEKEY";

        @Override
        public void onReceive(Context context, Intent intent)
        {
            String action = intent.getAction();
            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action))
            {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                if (SYSTEM_DIALOG_REASON_HOME_KEY.equals(reason))
                {
                    LogUtil.trace(TAG, "homePressReceiver!");
                    onHomePressed();
                }
            }
        }
    };

    /**
     * 设备断开回调函数
     */
    public void deviceDisconnect()
    {
        LogUtil.debug(TAG, "deviceDisconnect~~~~~~");
        SDKAPIUtil.getSystemControl().terminate();
    }

    /**
     * 设备连接回调函数
     */
    public void deviceConnected()
    {
        LogUtil.debug(TAG, "deviceConnected~~~~");
    }

    /**
     * 设备初始化失败回调函数
     */
    public void deviceInitFail()
    {
        LogUtil.debug(TAG, "deviceInitFail~~~~");
    }

    /**
     * 设备初始化OK回调函数
     */
    public void deviceInitOK()
    {
        LogUtil.debug(TAG, "deviceInitOK~~~~");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        LogUtil.debug(TAG, "onCreate~~~~~" + this);
        activityList.add(this);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        LogUtil.debug(TAG, "onResume~~~~~" + this);
        /* 注册home键监听 */
        final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(homePressReceiver, homeFilter);
        IntentFilter connectivityFilter = new IntentFilter();
        connectivityFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netConnectReceiver, connectivityFilter);
        LogUtil.debug(TAG, "onResume in BaseActivity");
    }

    @Override
    protected void onPause()
    {
        LogUtil.debug(TAG, "onPause~~~~~");
        super.onPause();
    }

    @Override
    protected void onStop()
    {
        LogUtil.debug(TAG, "onStop~~~~~" + this);
        try
        {
            unregisterReceiver(netConnectReceiver);
            unregisterReceiver(homePressReceiver);
        }
        catch (Exception e)
        {
            LogUtil.error(TAG, "onStop Exception " + e.getMessage());
        }
        super.onStop();
    }

    /**
     * 退出应用调用
     * @param background 是否退到后台，true表示退到后台，false表示不退到后台
     */
    public void exitLiveApp(boolean background)
    {
        LogUtil.debug(TAG, "exitLiveApp~~~~~~background:" + background);
        /* 如果dongle拔出，则直接退出整个应用 */
        FragmentUtil.popAllBackStack(getFragmentManager());
        if (SDKAPIUtil.getDVBDevice().isConnected() == false
                || isMediaPlayerError() == true || background == false)
        {
            LogUtil.error(TAG, "exitLiveApp~~~~~~bMediaPlayerError = " + isMediaPlayerError());

            for (Activity activity : activityList)
            {
                activity.finish();
            }

            SDKAPIUtil.getScanControl().abortScan();
            SDKAPIUtil.getSystemControl().standby(); // 释放TS流播放器
            System.exit(0);
        }
        else
        {
            for (Activity activity : activityList)
            {
                activity.finish();
            }
            SDKAPIUtil.getScanControl().abortScan();
            SDKAPIUtil.getSystemControl().standby(); // 释放TS流播放器
        }
    }

    /**
     * home键调用处理函数
     */
    void onHomePressed()
    {
        LogUtil.debug(TAG, "onHomePressed~~~~~~");
        exitLiveApp(true);
    }

    @Override
    protected void onDestroy()
    {
        LogUtil.debug(TAG, "onDestroy~~~~~" + this);
        activityList.remove(this);
        netConnectReceiver = null;
        homePressReceiver = null;
        super.onDestroy();
    }

    /**
     * 虚函数，获取player播放是否错误的状态
     * @return boolean
     */
    abstract boolean isMediaPlayerError();

    /**
     * 网络OK回调
     */
    abstract void onNetworkOk();

    /**
     * 网络断开回调
     */
    abstract void onNetworkFail();
}
